package org.example.linkedlist;

/**
 * @Description: TODO
 * @Author wyatt
 * @Data 2024/05/28 20:41
 */
@Deprecated
public class Solution21 {
    public static void main(String[] args) {
        Solution21 solution21 = new Solution21();
        ListNode res = solution21.mergeTwoLists(new ListNode(1, new ListNode(2))
                , new ListNode(1, new ListNode(3)));
        ListNode head = res;

        while (head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }

    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode prehead = new ListNode(-1);
        ListNode res = prehead;
        while (list1 != null && list2 != null){

            if(list1.val < list2.val){
                res.next = list1;
                list1 = list1.next;
            }else {
                res.next = list2;
                list2 = list2.next;
            }
            res = res.next;
        }

        res.next = list1 == null ? list2 : list1;
        return prehead.next;
    }


    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完，我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;

        return prehead.next;
    }

}

